/*
 * @Author: rock
 * @Date: 2025-05-17 16:14:54
 * @LastEditors: rock 
 * @LastEditTime: 2025-05-17 18:47:18
 * @FilePath: /001ConnPool/src/_____Connection.cpp
 * @Description: Ctrl+Num1-> For Document; Ctrl+Num2-> For Function
 *
 * Copyright (c) 2025 by rock, All Rights Reserved.
 */
#include "_____Connection.h"

// 初始化数据库连接
Connection::Connection()
{

    try
    {
        m_driver = sql::mysql::get_mysql_driver_instance();

        LOG("驱动加载成功");
    }
    catch (sql::SQLException &e)
    {
        LOG("数据库异常: " << e.what());
    }
    catch (std::exception &e)
    {
        LOG("系统异常: " << e.what());
    }
}

// 连接数据库
bool Connection::connect(
    std::string ip,       // 数据库ip
    unsigned short port,  // 数据库端口, 一般是3306
    std::string user,     // 数据库登录用户名
    std::string password, // 数据库密码
    std::string dbname    // 数据库的名称
)
{
    m_ip = ip;
    m_port = port;
    m_user = user;
    m_password = password;
    m_dbname = dbname;
    auto *con = m_driver->connect(m_ip, m_user, m_password);
    con->setSchema(dbname);
    m_con.reset(con);

    if (m_con != nullptr)
    {
        LOG("创建连接成功");
        return true;
    }
    return false;
}

// 更新操作
bool Connection::update(std::string sql_update)
{
    LOG("数据库更新操作" << sql_update);
    return false;
}

bool Connection::update_add(std::string sql_update_add)
{
    LOG("数据库更新, 增操作" << sql_update_add);

    try
    {
        // 开始事务
        m_con->setAutoCommit(false);        
        // 准备插入用户
        std::unique_ptr<sql::PreparedStatement> pstmt_insert(m_con->prepareStatement(sql_update_add));

        // 执行插入
        pstmt_insert->executeUpdate();
        // 提交事务
        m_con->commit();
        LOG("new user insert into user success");
        return true;
    }
    catch (std::exception e)
    {
        LOG(e.what());
    }
    return false;
}

bool Connection::update_del(std::string sql_update_del)
{
    LOG("数据库更新, 增操作" << sql_update_del);
    return false;
}

bool Connection::update_mod(std::string sql_update_mod)
{
    LOG("数据库更新, 增操作" << sql_update_mod);
    return false;
}

bool Connection::update_query(std::string sql_query)
{
    LOG("数据库查询操作" << sql_query);
    try
    {
        // 开始事务
        m_con->setAutoCommit(false);
        
        // 准备查询
        std::unique_ptr<sql::PreparedStatement> pstmt_query(m_con->prepareStatement(sql_query));

        // // 执行查询
        // pstmt_query->executeUpdate();

        // 执行查询
        std::unique_ptr<sql::ResultSet> res(pstmt_query->executeQuery());

        // 遍历结果集
        while (res->next())
        {
            LOG( "Check Email: " << res->getString("name"));            
        }
        // 提交事务
        m_con->commit();
        LOG("success to select");
        return true;
    }
    catch (std::exception e)
    {
        LOG(e.what());
    }
    return false;
}

// 释放数据库连接
Connection::~Connection()
{
    LOG("Connection 析构");
}